<?php
/**
 * 分页类 - JBlog
 *
 * @copyright (c) 2008-2012 JBlog (www.lisijie.org)
 * @author lisijie <lisijie86@gmail.com>
 * @version $Id: Page.php 11 2012-05-25 06:59:45Z lisijie86@gmail.com $
 */

class Pager {
	
	private $params = array();
	
	/**
	 * 构造方法
	 * @param int $page 当前页码
	 * @param int $count 记录数量
	 */
	public function __construct($curPage = 1, $totalNum = 0, $queryString = '') {
		if (is_array($queryString)) $queryString = http_build_query($queryString);
		$this->setParam('curPage', $curPage);
		$this->setParam('totalNum', $totalNum);
		$this->setParam('pageSize', 10);
		$this->setParam('linkNum', 10);
		$this->setParam('offset', 5);
		$this->setParam('queryString', $queryString);
	}
	
	public function setParam($name, $value) {
		$this->params[$name] = $value;
	}
	
	public function getParam($name) {
		return isset($this->params[$name]) ? $this->params[$name] : '';
	}
	
	private function makeUrl($page) {
		$query = $this->getParam('queryString');
		$query .= '&page='.intval($page);
		return url($query, CONTROL_NAME.'.'.ACTION_NAME);
	}
	
	/**
	 * 返回显示分页HTML
	 */
	public function makeHtml() {
		$totalNum = $this->getParam('totalNum');
		$pageSize = $this->getParam('pageSize');
		$linkNum  = $this->getParam('linkNum');
		$curPage  = $this->getParam('curPage');
		$pagestr = '';
		$totalPage = 1;
		if ($totalNum > $pageSize) {
			$totalPage = @ceil($totalNum / $pageSize);
			if ($totalPage < $linkNum) {
				$from = 1;
				$to = $totalPage;
			} else {
				$from = $curPage - $this->getParam('offset');
				$to = $from + $linkNum;
				if ($from < 1) {
					$from = 1;
					$to = $from + $linkNum - 1;
				} elseif ($to > $totalPage) {
					$to = $totalPage;
					$from = $totalPage - $linkNum + 1;
				}
			}
			$pagestr .= '<span>'.$totalNum.'</span>';
			if ($curPage > $linkNum) $pagestr .= sprintf('<a href="%s">1...</a>', $this->makeUrl(1));
			if ($curPage > 1) $pagestr .= sprintf('<a href="%s">&lsaquo;&lsaquo;</a>', $this->makeUrl($curPage-1));
			for ($i = $from; $i <= $to; $i++) {
				if ($i == $curPage) {
					$pagestr .= sprintf('<span class="on">%s</span>', $i);
				} else {
					$pagestr .= sprintf('<a href="%s">%s</a>', $this->makeUrl($i), $i);
				}
			}
			if ($curPage < $totalPage) $pagestr .= sprintf('<a href="%s">&rsaquo;&rsaquo;</a>', $curPage+1);
			if ($totalPage > $to) $pagestr .= sprintf('<a href="%s">%s...</a>', $totalPage, $totalPage);
			$pagestr = '<div class="multipage">'.$pagestr.'</div>';
		}
		return $pagestr;
	}
}
